const MoneyTransfer = require("../models/moneyTransferModel");
const Account = require("../models/accountModel");

// CREATE Money Transfer
exports.createMoneyTransfer = async (req, res) => {
  try {
    const {
      transferDate,
      transferCode,
      debitAccount,
      creditAccount,
      amount,
      referenceNo,
      note
    } = req.body;

    // Basic validations
    if (!transferDate || !transferCode || !debitAccount || !creditAccount || !amount) {
      return res.status(400).json({ success: false, message: "Missing required fields" });
    }
    if (debitAccount === creditAccount) {
      return res.status(400).json({ success: false, message: "Debit and credit accounts cannot be the same" });
    }

    // Optional: Validate accounts exist
    const debitAccDoc = await Account.findById(debitAccount);
    if (!debitAccDoc) {
      return res.status(400).json({ success: false, message: "Invalid debit account" });
    }
    const creditAccDoc = await Account.findById(creditAccount);
    if (!creditAccDoc) {
      return res.status(400).json({ success: false, message: "Invalid credit account" });
    }

    // Set createdBy and createdByModel if authenticated
    let createdBy = null;
    let createdByModel = null;
    if (req.user && req.user.id) {
      createdBy = req.user.id;
      createdByModel = req.user.role.toLowerCase() === "admin" ? "Admin" : "User";
    }

    const newTransfer = new MoneyTransfer({
      transferDate,
      transferCode,
      debitAccount,
      creditAccount,
      amount,
      referenceNo,
      note,
      createdBy,
      createdByModel
    });

    const savedTransfer = await newTransfer.save();
    return res.status(201).json({ success: true, message: "Money Transfer created", data: savedTransfer });
  } catch (error) {
    console.error("Error creating money transfer:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

// GET All Money Transfers (with creatorName computed)
exports.getAllTransfers = async (req, res) => {
  try {
    const transfers = await MoneyTransfer.find()
      .populate("debitAccount", "accountName accountNumber")
      .populate("creditAccount", "accountName accountNumber")
      .populate("createdBy", "FirstName LastName name");
    
    // Compute creatorName for each transfer
    const processedTransfers = transfers.map((transfer) => {
      let creatorName = "";
      if (transfer.createdBy) {
        if (transfer.createdBy.name) {
          creatorName = transfer.createdBy.name;
        } else if (transfer.createdBy.FirstName && transfer.createdBy.LastName) {
          creatorName = `${transfer.createdBy.FirstName} ${transfer.createdBy.LastName}`;
        }
      }
      return { ...transfer.toObject(), creatorName };
    });

    return res.status(200).json({ success: true, data: processedTransfers });
  } catch (error) {
    console.error("Error fetching transfers:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

// GET Single Money Transfer (with creatorName computed)
exports.getTransferById = async (req, res) => {
  try {
    const transfer = await MoneyTransfer.findById(req.params.id)
      .populate("debitAccount", "accountName accountNumber")
      .populate("creditAccount", "accountName accountNumber")
      .populate("createdBy", "FirstName LastName name");
    if (!transfer) {
      return res.status(404).json({ success: false, message: "Transfer not found" });
    }
    let creatorName = "";
    if (transfer.createdBy) {
      if (transfer.createdBy.name) {
        creatorName = transfer.createdBy.name;
      } else if (transfer.createdBy.FirstName && transfer.createdBy.LastName) {
        creatorName = `${transfer.createdBy.FirstName} ${transfer.createdBy.LastName}`;
      }
    }
    return res.status(200).json({ success: true, data: { ...transfer.toObject(), creatorName } });
  } catch (error) {
    console.error("Error fetching transfer:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

// UPDATE Money Transfer
exports.updateTransfer = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      transferDate,
      transferCode,
      debitAccount,
      creditAccount,
      amount,
      referenceNo,
      note
    } = req.body;

    const updated = await MoneyTransfer.findByIdAndUpdate(
      id,
      { transferDate, transferCode, debitAccount, creditAccount, amount, referenceNo, note },
      { new: true }
    )
      .populate("debitAccount", "accountName accountNumber")
      .populate("creditAccount", "accountName accountNumber")
      .populate("createdBy", "FirstName LastName name");

    if (!updated) {
      return res.status(404).json({ success: false, message: "Transfer not found" });
    }
    let creatorName = "";
    if (updated.createdBy) {
      if (updated.createdBy.name) {
        creatorName = updated.createdBy.name;
      } else if (updated.createdBy.FirstName && updated.createdBy.LastName) {
        creatorName = `${updated.createdBy.FirstName} ${updated.createdBy.LastName}`;
      }
    }
    return res.status(200).json({ success: true, message: "Transfer updated", data: { ...updated.toObject(), creatorName } });
  } catch (error) {
    console.error("Error updating transfer:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

// DELETE Money Transfer
exports.deleteTransfer = async (req, res) => {
  try {
    const deleted = await MoneyTransfer.findByIdAndDelete(req.params.id);
    if (!deleted) {
      return res.status(404).json({ success: false, message: "Transfer not found" });
    }
    return res.status(200).json({ success: true, message: "Transfer deleted" });
  } catch (error) {
    console.error("Error deleting transfer:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};
